package com.lan.viewObject;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * 分页处理对象.
 *
 * @author Shadow
 */
@Data
public class Pager implements Serializable {

    private static final long serialVersionUID = 7413934001843897320L;
    /**
     * 总记录数.
     **/
    private Long totalCount;
    /**
     * 每页记录数.
     **/
    private Long pageSize;
    /**
     * 总页数.
     **/
    private Long totalPage;
    /**
     * 当前页数.
     **/
    private Long currPage;
    /**
     * 列表数据.
     **/
    private List<?> list;

    public Pager() {
    }

    /**
     * 分页.
     * @param list        列表数据
     * @param totalCount  总记录数
     * @param pageSize    每页记录数
     * @param currPage    当前页数
     */
    public Pager(final List<?> list, final Long totalCount, final Long pageSize, final Long currPage) {
        this.list = list;
        this.totalCount = totalCount;
        this.pageSize = pageSize;
        this.currPage = currPage;
        this.totalPage = Math.abs(totalCount / pageSize);
    }

    /**
     * 分页信息获取.
     * @param page 分页对象
     */
    public Pager(final IPage<?> page) {
        this.list = page.getRecords();
        this.totalCount = page.getTotal();
        this.pageSize = page.getSize();
        this.currPage = page.getCurrent();
        this.totalPage = page.getPages();
    }

    /**
     * 转为分页对象
     * @param params 参数
     * @param list 结果集
     * @return 分页对象
     */
    public static Pager getPager(Map<String, Object> params, List<? extends Pages> list) {
        Pager pager = new Pager();
        if (CollectionUtils.isNotEmpty(list)) {
            pager.setList(list);
            pager.setCurrPage(Long.valueOf((Integer) params.get("page")));
            pager.setPageSize(Long.valueOf((Integer) params.get("limit")));
            pager.setTotalCount(list.get(0).getTotalCount());
            pager.setTotalPage(list.get(0).getTotalPage());
        }
        return pager;
    }
}
